package com.taotao.antlr4.calcu;

import java.util.Deque;
import java.util.LinkedList;

public class MyCalculatorListener extends CalculatorBaseListener {

    private final Deque<Double> stack = new LinkedList<>();

    /**
     * The last value on the stack is the result of all applied calculations.
     *
     * @return Integer
     */
    public Double getResult() {
        return this.stack.peek();
    }

    @Override
    public void exitMulDiv(CalculatorParser.MulDivContext ctx) {
        Double right = this.stack.pop();
        Double left = this.stack.pop();
        if (ctx.op.getType() == CalculatorParser.MUL) {
            this.stack.push(left * right);
        } else {
            this.stack.push(left / right);
        }
    }

    @Override
    public void exitAddSub(CalculatorParser.AddSubContext ctx) {
        Double right = this.stack.pop();
        Double left = this.stack.pop();
        if (ctx.op.getType() == CalculatorParser.ADD) {
            this.stack.push(left + right);
        } else {
            this.stack.push(left - right);
        }
    }



    @Override public void exitNumber(CalculatorParser.NumberContext ctx) {
        Double number = Double.parseDouble(ctx.NUMBER().getText());
        this.stack.push(number);
    }
}